from sqlalchemy.orm import Session
from .. import models, schemas
from ..utils.security import get_password_hash, verify_password
from fastapi import HTTPException, status

def get_user(db: Session, user_id: str):
    return db.query(models.User).filter(models.User.id == user_id).first()

def get_user_by_username(db: Session, username: str):
    return db.query(models.User).filter(models.User.username == username).first()

def create_user(db: Session, user: schemas.UserCreate):
    """创建新用户"""
    # 检查用户名是否已存在
    if get_user_by_username(db, username=user.username):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户名已存在"
        )
    
    # 对密码进行哈希处理
    hashed_password = get_password_hash(user.password)
    
    # 创建用户对象，确保 gender 是整数
    db_user = models.User(
        username=user.username,
        password=hashed_password,
        gender=int(user.gender),  # 确保转换为整数
        bio=user.bio
    )
    
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

def authenticate_user(db: Session, username: str, password: str):
    user = get_user_by_username(db, username)
    if not user:
        return False
    if not verify_password(password, user.password):
        return False
    return user

async def update_user(db: Session, user_id: str, user_data: schemas.UserUpdate):
    """更新用户资料"""
    db_user = get_user(db, user_id)
    if not db_user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 更新用户资料
    update_data = user_data.dict(exclude_unset=True)
    for field, value in update_data.items():
        if field == 'gender' and value is not None:
            value = int(value)  # 确保性别是整数
        setattr(db_user, field, value)
    
    db.commit()
    db.refresh(db_user)
    return db_user

def update_user_image(db: Session, user_id: str, profile_image: str):
    """更新用户头像"""
    user = get_user(db, user_id)
    user.profile_image = profile_image
    db.commit()
    db.refresh(user)
    return user 